import os

from langchain.tools import Tool
from langchain_community.utilities import SerpAPIWrapper
from langchain_core.tools import tool

#第三方API工具
os.environ["OPENAI_API_KEY"] = os.environ["OPENAI_API_KEY_ZHIHU"]
os.environ["OPENAI_API_BASE"] = os.environ["OPENAI_API_BASE_ZHIHU"]
os.environ["SERPAPI_API_KEY"] = 'a01032707e956769e459a23034f3bbda54a364b02cb0dd4ab4b6b42800f6d774'

search = SerpAPIWrapper()
tools = [
    Tool.from_function(
        name="Intermediate Answer",
        func=search.run,
        description="搜素引擎",
        max_results=1
    ),
]


#获取 Agent提示模板
from langchain import hub
import json

# 下载一个现有的 Prompt 模板
self_ask_prompt = hub.pull("hwchase17/self-ask-with-search")
# print(self_ask_prompt.template)


from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor,create_self_ask_with_search_agent


llm = ChatOpenAI(model_name='gpt-4o', temperature=0, model_kwargs={"seed":23})

# 定义一个 agent: 需要大模型、工具集、和 Prompt 模板
agent = create_self_ask_with_search_agent(llm, tools, self_ask_prompt)
# 定义一个执行器：需要 agent 对象 和 工具集
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True,handle_parsing_errors=True)

# 执行
agent_executor.invoke({"input": "冯小刚的老婆演过哪些电影，用中文回答"})